//
//  EmoticonController.swift
//  表情键盘
//
//  Created by 万佳阳 on 16/8/5.
//  Copyright © 2016年 JYWan. All rights reserved.
//

import UIKit

private let EmoticonCellID = "emoticonCell"

class EmoticonController: UIViewController {
    // MARK:- 定义属性
    var emoticonCallBack : (emoticon : Emoticon) -> ()
    
    // MARK:- 懒加载属性
    private lazy var collectionView : UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: EmoticonCollectionViewLayout())
    private lazy var toolbar : UIToolbar = UIToolbar()
    private lazy var emoticonManager : EmoticonManager = EmoticonManager()

    //自定义构造函数
    init(emoticonCallBack : (emoticon : Emoticon) -> ()) {
        self.emoticonCallBack = emoticonCallBack
        
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // MARK:- 系统回调函数
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
        
        collectionView.backgroundColor = UIColor.purpleColor()
        toolbar.backgroundColor = UIColor.darkGrayColor()
        
    }

}

// MARK:- 设置UI界面
extension EmoticonController {
    private func setupUI() {
        //添加子控件
        view.addSubview(collectionView)
        view.addSubview(toolbar)
        
        //设置子控件约束
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolbar.translatesAutoresizingMaskIntoConstraints = false
        let views = ["collectionView" : collectionView, "toolbar" : toolbar]
        var cons = NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[toolbar]-0-|", options: [], metrics: nil, views: views)
        cons += NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[collectionView]-0-[toolbar]-0-|", options: [.AlignAllLeading, .AlignAllTrailing], metrics: nil, views: views)
        view.addConstraints(cons)
        
        //准备collectionView
        prepareCollerctionView()
        
        //准备toolbar
        prepareToolbar()
    }
    
    private func prepareCollerctionView() {
        //注册cell
        collectionView.registerClass(EmoticonViewCell.self, forCellWithReuseIdentifier: EmoticonCellID)
        
        collectionView.dataSource = self
        collectionView.delegate = self
    }
    
    private func prepareToolbar() {
        //定义item标题
        let titles = ["最近", "默认", "emoji", "浪小花"]
        
        //创建item
        var index = 0
        var tempItems = [UIBarButtonItem]()
        
        for title in titles {
            let item = UIBarButtonItem(title: title, style: .Plain, target: self, action: #selector(EmoticonController.itemClick(_:)))
            item.tag = index
            index += 1
            tempItems.append(item)
            tempItems.append(UIBarButtonItem(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        //设置toolbar的item数组
        tempItems.removeLast()
        toolbar.items = tempItems
        toolbar.tintColor = UIColor.orangeColor()
    }
    
    @objc private func itemClick(item : UIBarButtonItem) {
        //获取item对应tag
        let tag = item.tag
        
        //根据tag获取当前组
        let indexpath = NSIndexPath(forItem: 0, inSection: tag)
        
        //滚动到对应位置
        collectionView.scrollToItemAtIndexPath(indexpath, atScrollPosition: .Left, animated: true)
        
    }
}

// MARK:- collectionView数据源,代理方法
extension EmoticonController :UICollectionViewDataSource, UICollectionViewDelegate {
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        
        return emoticonManager.packages.count
    }
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let package = emoticonManager.packages[section]
    
        return package.emoticons.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmoticonCellID, forIndexPath: indexPath) as! EmoticonViewCell
        
        //给cell设置数据
        let package = emoticonManager.packages[indexPath.section]
        cell.emoticon = package.emoticons[indexPath.item]
        
        return cell
        
    }
    
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        //取出点击到表情
        let package = emoticonManager.packages[indexPath.section]
        let emoticon = package.emoticons[indexPath.item]
        
        //将点击到表情插入最近分组中
        insertRecentlyEmoticon(emoticon)
        
        //将点击的表情回调出去
        emoticonCallBack(emoticon: emoticon)
    }
    
    private func insertRecentlyEmoticon(emoticon : Emoticon) {
        //如果是空表情或者删除表情不需要插入
        if emoticon.isRemove || emoticon.isEmpty {
            return
        }
        
        //删除一个表情
        if emoticonManager.packages.first!.emoticons.contains(emoticon) { //原来有该表情
            let index = (emoticonManager.packages.first?.emoticons.indexOf(emoticon))!
            emoticonManager.packages.first?.emoticons.removeAtIndex(index)
        } else {
            emoticonManager.packages.first?.emoticons.removeAtIndex(19)
        }
        
        //插入到最近分组中
        emoticonManager.packages.first?.emoticons.insert(emoticon, atIndex: 0)
    }
}


class EmoticonCollectionViewLayout: UICollectionViewFlowLayout {
    override func prepareLayout() {
        super.prepareLayout()
        
        //计算item
        let itemWH = UIScreen.mainScreen().bounds.width / 7
        
        //设置layout属性
        itemSize = CGSize(width: itemWH, height: itemWH)
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        scrollDirection = .Horizontal
        
        //设置collectionView的属性
        collectionView?.pagingEnabled = true
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.showsHorizontalScrollIndicator = false
        let edgeMargin = (collectionView!.bounds.height - 3 * itemWH) * 0.5
        collectionView?.contentInset = UIEdgeInsets(top: edgeMargin, left: 0, bottom: edgeMargin, right: 0)
        
        
    }
}




